#!/bin/bash
#----------------------------------*-sh-*--------------------------------------
# =========                 |
# \\      /  F ield         | foam-extend: Open Source CFD
#  \\    /   O peration     | Version:     4.1
#   \\  /    A nd           | Web:         http://www.foam-extend.org
#    \\/     M anipulation  | For copyright notice see file Copyright
#------------------------------------------------------------------------------
# License
#     This file is part of foam-extend.
#
#     foam-extend is free software: you can redistribute it and/or modify it
#     under the terms of the GNU General Public License as published by the
#     Free Software Foundation, either version 3 of the License, or (at your
#     option) any later version.
#
#     foam-extend is distributed in the hope that it will be useful, but
#     WITHOUT ANY WARRANTY; without even the implied warranty of
#     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
#     General Public License for more details.
#
#     You should have received a copy of the GNU General Public License
#     along with foam-extend.  If not, see <http://www.gnu.org/licenses/>.
#
# Script
#     etc/bashrc
#
# Description
#     Startup file for FOAM
#     Sourced from ~/.profile or ~/.bashrc
#     Should be usable by any POSIX-compliant shell (eg, ksh)
#
#------------------------------------------------------------------------------

export WM_PROJECT=foam
export WM_FORK='x4m'
export WM_PROJECT_VERSION=4.1

foamInstall=`cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd`

###############################################################################
# USER EDITABLE PART
#
# either set $FOAM_INST_DIR before sourcing this file or set
#    $foamInstall below to where FOAM is installed
#
# Location of FOAM installation
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#foamInstall=/opt/FOAM
# foamInstall=~$WM_PROJECT
# foamInstall=/usr/local/$WM_PROJECT
# foamInstall=/opt/$WM_PROJECT
# foamInstall=/usr/lib
#
# END OF (NORMAL) USER EDITABLE PART
################################################################################

# Set $USER if it has not been set (eg. on Windows/MSYS systems)
if [ -z $USER ]
then
    export USER=`whoami`
fi

# note the location for later use (eg, in job scripts)
: ${FOAM_INST_DIR:=$foamInstall}; export FOAM_INST_DIR

# The old dirs to be cleaned from the various environment variables
# - remove anything under top-level directory.
# NB: the WM_PROJECT_INST_DIR might not be identical between versions
foamOldDirs="$FOAM_INST_DIR $HOME/$WM_PROJECT/$USER"
if [ "$WM_PROJECT_INST_DIR" != "$FOAM_INST_DIR" ]
then
    foamOldDirs="$WM_PROJECT_INST_DIR $foamOldDirs"
fi


# Location of site/user files
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~
export WM_PROJECT_INST_DIR=$FOAM_INST_DIR
export WM_PROJECT_DIR=$WM_PROJECT_INST_DIR/$WM_PROJECT$WM_FORK
export WM_PROJECT_USER_DIR=$HOME/$WM_PROJECT/$USER$WM_FORK

# Location of third-party software
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#: ${WM_THIRD_PARTY_DIR=$WM_PROJECT_INST_DIR/ThirdParty-$WM_PROJECT_VERSION}; export WM_THIRD_PARTY_DIR
export WM_THIRD_PARTY_DIR=$WM_PROJECT_DIR/ThirdParty

# Enabling the usage of third-party software
# This can be overriden in prefs.sh
# Use 'set' and 'unset' to adjust for your environent
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# For AllMake.stage1
#export WM_THIRD_PARTY_USE_CMAKE_322=1

#
# For AllMake.stage2
export WM_THIRD_PARTY_USE_OPENMPI_188=1

#
# For AllMake.stage3
export WM_THIRD_PARTY_USE_METIS_510=1
export WM_THIRD_PARTY_USE_PARMGRIDGEN_10=1
export WM_THIRD_PARTY_USE_LIBCCMIO_261=1
export WM_THIRD_PARTY_USE_MESQUITE_230=1
export WM_THIRD_PARTY_USE_SCOTCH_604=1
export WM_THIRD_PARTY_USE_PARMETIS_403=1
export WM_THIRD_PARTY_USE_PYFOAM_069=1
export WM_THIRD_PARTY_USE_HWLOC_201=1

#
# For AllMake.stage4
#export WM_THIRD_PARTY_USE_QT_5111=1
#export WM_THIRD_PARTY_USE_PARAVIEW_552=1


# Source files, possibly with some verbosity
_foamSource()
{
   while [ $# -ge 1 ]
   do
      [ "$FOAM_VERBOSE" -a "$PS1" ] && echo "Sourcing: $1" 1>&2
      . $1
      shift
   done
}

# Add in preset user or site preferences:
if [ "$WM_OSTYPE" == "MSWindows" ]
then
    _foamSource $WM_PROJECT_DIR/etc/prefs.sh.mingw
	export WM_ARCH=mingw
elif [ -e $WM_PROJECT_DIR/etc/prefs.sh ]
then
    _foamSource $WM_PROJECT_DIR/etc/prefs.sh
	export WM_ARCH=`uname -s`
else
     [ "$FOAM_VERBOSE" -a "$PS1" ] && echo "No prefs.sh found"

	# Detect system type and set environment variables appropriately
	# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	export WM_ARCH=`uname -s`

fi


# Evaluate command-line parameters
while [ $# -gt 0 ]
do
    case "$1" in
    *=)
        # name=       -> unset name
        eval "unset ${1%=}"
        ;;
    *=*)
        # name=value  -> export name=value
        eval "export $1"
        ;;
    esac
    shift
done


# Operating System/Platform
# ~~~~~~~~~~~~~~~~~~~~~~~~~
# WM_OSTYPE = POSIX | ????
: ${WM_OSTYPE:=POSIX}; export WM_OSTYPE


# Compiler: set to Gcc, Icc (for Intel's icc) or Clang
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
: ${WM_COMPILER:=Gcc}; export WM_COMPILER
#: ${WM_COMPILER:=Icc}; export WM_COMPILER

export WM_COMPILER_ARCH=
export WM_COMPILER_LIB_ARCH=


# Compilation options (architecture, precision, optimised, debug or profiling)
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

# WM_ARCH_OPTION = 32 | 64
: ${WM_ARCH_OPTION:=64}; export WM_ARCH_OPTION

# WM_PRECISION_OPTION = DP | SP
: ${WM_PRECISION_OPTION:=DP}; export WM_PRECISION_OPTION

#    WM_LABEL_SIZE = 32 | 64
: ${WM_LABEL_SIZE:=32}; export WM_LABEL_SIZE

# WM_COMPILE_OPTION = Opt | Debug | Prof
: ${WM_COMPILE_OPTION:=Opt}; export WM_COMPILE_OPTION

# WM_MPLIB = SYSTEMOPENMPI | OPENMPI | INTELMPI | MPICH | MPICH-GM | HPMPI | GAMMA | MPI | QSMPI | MVAPICH2
: ${WM_MPLIB:=SYSTEMOPENMPI}; export WM_MPLIB

# WM_NCOMPPROCS = <number of processes to use>
# Warning: Need to use a complete path for foamGetSystemInfo because the PATH
# environment variable is not properly initialized yet.
: ${WM_NCOMPPROCS:=`$WM_PROJECT_DIR/bin/foamGetSystemInfo -nbrCores`}; export WM_NCOMPPROCS


# Run options (floating-point signal handling and memory initialisation)
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
export FOAM_SIGFPE=
# export FOAM_SETNAN=



case $WM_ARCH in
Linux)
    WM_ARCH=linux

    # compiler specifics
    case `uname -m` in
    i686)
        ;;

    x86_64)
        case $WM_ARCH_OPTION in
        32)
            export WM_COMPILER_ARCH='-64'
            export WM_CFLAGS='-m32 -fPIC'
            export WM_CXXFLAGS='-m32 -fPIC'
            export WM_LDFLAGS='-m32'
            ;;
        64)
            WM_ARCH=linux64
            export WM_COMPILER_LIB_ARCH=64
            export WM_CFLAGS='-m64 -fPIC'
            export WM_CXXFLAGS='-m64 -fPIC'
            export WM_LDFLAGS='-m64'
            ;;
        *)
            echo Unknown WM_ARCH_OPTION $WM_ARCH_OPTION, should be 32 or 64
            ;;
        esac
        ;;

    ia64)
        WM_ARCH=linuxIA64
        export WM_COMPILER=I64
        ;;

    mips64)
        WM_ARCH=SiCortex64
        export WM_COMPILER_LIB_ARCH=64
        export WM_CFLAGS='-mabi=64 -fPIC'
        export WM_CXXFLAGS='-mabi=64 -fPIC'
        export WM_LDFLAGS='-mabi=64 -G0'
        export WM_MPLIB=MPI
        ;;

    ppc64)
        WM_ARCH=linuxPPC64
        export WM_COMPILER_LIB_ARCH=64
        export WM_CFLAGS='-m64 -fPIC'
        export WM_CXXFLAGS='-m64 -fPIC'
        export WM_LDFLAGS='-m64'
        ;;

    *)
        echo Unknown processor type `uname -m` for Linux
        ;;
    esac
    ;;

Darwin)
    # this makes certain things easier
    export WM_ARCH_BASE=darwin

    case `uname -p` in
    powerpc)
        export WM_ARCH=darwinPpc
    ;;
    i386)
        export WM_ARCH=darwinIntel
    ;;
    *)
        echo "This seems to be neither an Intel-Mac nor a PPC-Mac please tell me the output of 'uname -p'. Bernhard."
        export WM_ARCH=darwinUnknown
    ;;
    esac

    case $WM_ARCH_OPTION in
    32)
        export WM_CFLAGS='-m32 -fPIC'
        export WM_CXXFLAGS='-m32 -fPIC'
        export WM_LDFLAGS='-m32'
    ;;
    64)
        export WM_ARCH=${WM_ARCH}64
        export WM_CFLAGS='-m64 -fPIC'
        export WM_CXXFLAGS='-m64 -fPIC'
        export WM_LDFLAGS='-m64'
    ;;
    *)
        echo Unknown WM_ARCH_OPTION $WM_ARCH_OPTION, should be 32 or 64
    ;;
    esac

    # Using MacPorts
    : ${MACOSX_MACPORTS_ROOT:='/opt/local/etc/macports'}; export MACOSX_MACPORTS_ROOT
    which -s port >/dev/null
    if [ $? -eq "0" ]  && [ -d "$MACOSX_MACPORTS_ROOT" ]
    then
	if [ "$FOAM_VERBOSE" -a "$PS1" ]
	then
	    echo "Using Macports binaries"
	fi

	export WM_USE_MACPORT=0
	export WM_BASE_COMPILER=`echo $WM_COMPILER | tr -d "[:digit:]"`
	export WM_MACPORT_MPI_VERSION=`echo $WM_COMPILER | tr "[:upper:]" "[:lower:]"`
	export WM_MACPORT_VERSION=`echo $WM_MACPORT_MPI_VERSION | tr -d "[:alpha:]" | sed -e "s/\(.\)\(.\)/\1\.\2/"`

	if [ -z "$WM_CHOSEN_MAC_MPI" ]
	then
	    if [ -e '/opt/local/bin/mpicc' ]
	    then
		readlink /opt/local/bin/mpicc | grep openmpi >/dev/null
		if [ $? -eq "0" ]
		then
		    export WM_MPLIB=MACPORTOPENMPI
		    if [ "$FOAM_VERBOSE" -a "$PS1" ]
		    then
			echo "Using OpenMPI from MacPorts"
		    fi
		else
		    readlink /opt/local/bin/mpicc | grep mpich >/dev/null
		    if [ $? -eq "0" ]
		    then
			export WM_MPLIB=MACPORTMPICH
			if [ "$FOAM_VERBOSE" -a "$PS1" ]
			then
			    echo "Using MPICH from MacPorts"
			fi
		    else
			echo "/opt/local/bin/mpicc neither OpenMPI nor MPICH. Confused. Defaulting to OPENMPI"
			export WM_MPLIB=OPENMPI
		    fi
		fi
	    fi
	else
	    export WM_MPLIB=$WM_CHOSEN_MAC_MPI
	    if [ "$FOAM_VERBOSE" -a "$PS1" ]
	    then
		echo "User chose WM_CHOSEN_MAC_MPI=$WM_CHOSEN_MAC_MPI"
	    fi
	fi

	if [ "$WM_MPLIB" == "MACPORTOPENMPI" ]
	then
	    if [ ! -e "/opt/local/lib/openmpi-$WM_MACPORT_MPI_VERSION" ]
	    then
		export WM_MACPORT_MPI_VERSION=mp
		if [ ! -e "/opt/local/lib/openmpi-$WM_MACPORT_MPI_VERSION" ]
		then
		    echo "Proper OpenMPI not installed. Either do 'port install openmpi-$WM_MACPORT_MPI_VERSION' or 'port install openmpi-default'"
		fi
	    fi
	else
	    if [ "$WM_MPLIB" == "MACPORTMPICH" ]
	    then
		if [ ! -e "/opt/local/lib/mpich-$WM_MACPORT_MPI_VERSION" ]
		then
		    echo "MPICH wants the same version as the used compiler. Do 'port install mpich-$WM_MACPORT_MPI_VERSION'"
		fi
	    fi
	fi

	if [ "$WM_COMPILER" != "Gcc" ]
	then
		if [ "$WM_BASE_COMPILER" == "Gcc" ] 
		then
			export WM_CC="gcc-mp-$WM_MACPORT_VERSION"
			export WM_CXX="g++-mp-$WM_MACPORT_VERSION"
			export WM_FC="gfortran-mp-$WM_MACPORT_VERSION"
		elif [ "$WM_BASE_COMPILER" == "Clang" ]
		then
			if [ "$WM_USE_MACPORT" == "1" ]
			then
				export WM_CC="clang-mp-$WM_MACPORT_VERSION"
				export WM_CXX="clang++-mp-$WM_MACPORT_VERSION"
			else
				export WM_CC="clang"
				export WM_CXX="clang++"
			fi
		# Seems like there is no Fortran-frontend for LLVM at thistime
	    elif [ "$WM_BASE_COMPILER" == "Dragonegg" ]
	    then
		export WM_CC="dragonegg-$WM_MACPORT_VERSION-gcc"
		export WM_CXX="dragonegg-$WM_MACPORT_VERSION-g++"
		export WM_CXX="dragonegg-$WM_MACPORT_VERSION-gfortran"
	    else
		echo "Unknown base compiler $WM_BASE_COMPILER"
	    fi

	    ruleDirBase=$WM_PROJECT_DIR/wmake/rules/$WM_ARCH
	    ruleDirTarget=$ruleDirBase$WM_BASE_COMPILER
	    ruleDir=$ruleDirBase$WM_COMPILER
	    if [ ! -e $ruleDir ]
	    then
		echo "Rule directory $ruleDir not existing. Linking to $ruleDirTarget"
		ln -s $ruleDirTarget $ruleDir
	    fi
	    unset ruleDir ruleDirBase
	fi
    else
        echo "Warning: You are not using MacPorts. Make sure your compilation and MPI environment is correctly initialized"
    fi

    # Make sure that binaries use the best features of the used OS-Version
    # We need to get rid of the revision number from this string. eg turn "10.7.5" into "10.7"
    #    v=(`sw_vers -productVersion | sed 's/\./ /g'`)
    #    export MACOSX_DEPLOYMENT_TARGET="${v[1]}.${v[2]}"
    export MACOSX_DEPLOYMENT_TARGET=`sw_vers -productVersion | sed -e "s/\([0-9][0-9]*\)\.\([0-9][0-9]*\)\.\([0-9][0-9]*\)/\1.\2/g"`
    ;;

SunOS)
    WM_ARCH=SunOS64
    export WM_COMPILER_LIB_ARCH=64
    export WM_CFLAGS='-mabi=64 -fPIC'
    export WM_CXXFLAGS='-mabi=64 -fPIC'
    export WM_LDFLAGS='-mabi=64 -G0'
    export WM_MPLIB=FJMPI
    ;;

mingw)
		export WM_COMPILER_LIB_ARCH=64
		export WM_CFLAGS='-m64 -fPIC'
		export WM_CXXFLAGS='-m64 -fPIC'
		export WM_LDFLAGS='-m64'
      export WM_MPLIB=
    ;;

*)  # an unsupported operating system
    cat <<USAGE

    Your "$WM_ARCH" operating system is not supported by this release
    of foam-extend. For further assistance, please contact www.foam-extend.org

USAGE
    ;;
esac


# Clean standard environment variables (PATH, LD_LIBRARY_PATH, MANPATH)
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
cleanProg=$WM_PROJECT_DIR/bin/foamCleanPath

#- Clean PATH
cleanEnv=`$cleanProg "$PATH" "$foamOldDirs"` && PATH="$cleanEnv"

#- Clean LD_LIBRARY_PATH
cleanEnv=`$cleanProg "$LD_LIBRARY_PATH" "$foamOldDirs"` && LD_LIBRARY_PATH="$cleanEnv"

#- Clean DYLD_LIBRARY_PATH
if [[ "$WM_ARCH_BASE" == "darwin" ]]
then
    cleanEnv=`$cleanProg "$DYLD_LIBRARY_PATH" "$foamOldDirs"` && DYLD_LIBRARY_PATH="$cleanEnv"
fi

#- Clean MANPATH
cleanEnv=`$cleanProg "$MANPATH" "$foamCleanDirs"` && MANPATH="$cleanEnv"

export PATH LD_LIBRARY_PATH MANPATH

# Source project setup files
# ~~~~~~~~~~~~~~~~~~~~~~~~~~

_foamSource $WM_PROJECT_DIR/etc/settings.sh
_foamSource $WM_PROJECT_DIR/etc/aliases.sh


# Source user setup files for optional packages
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# _foamSource $WM_PROJECT_DIR/etc/apps/paraview/bashrc
# _foamSource $WM_PROJECT_DIR/etc/apps/paraview3/bashrc
# _foamSource $WM_PROJECT_DIR/etc/apps/ensight/bashrc


# Clean environment paths again. Only remove duplicates
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#- Clean PATH
cleanEnv=`$cleanProg "$PATH"` && PATH="$cleanEnv"

#- Clean LD_LIBRARY_PATH
cleanEnv=`$cleanProg "$LD_LIBRARY_PATH"` && LD_LIBRARY_PATH="$cleanEnv"

#- Clean MANPATH
cleanEnv=`$cleanProg "$MANPATH"` && MANPATH="$cleanEnv:"

export PATH LD_LIBRARY_PATH MANPATH

#- Clean LD_PRELOAD
if [ "$LD_PRELOAD" != "" ]
then
    cleanEnv=`$cleanProg "$LD_PRELOAD"` && LD_PRELOAD="$cleanEnv"
    export LD_PRELOAD
fi

# temporarily disabled.  HJ, 13/Jun/2014
# if [[ `uname -s` == "Darwin" ]]
# then
#     if [[ `ulimit -n` == "unlimited" || `ulimit -n` < 8192 ]]
#     then
#     # higher limit needed for wmkdeps
#     ulimit -n 8192
#     fi
# fi

# cleanup environment:
# ~~~~~~~~~~~~~~~~~~~~
unset cleanEnv cleanProg foamInstall foamOldDirs
unset _foamSource

# -----------------------------------------------------------------------------
